﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PublicEntity
{
    /// <summary>
    /// Socket发送的文件
    /// </summary>
    public class SocketFile
    {
        /// <summary>
        /// 文件的byte表示形式
        /// </summary>
        public byte[] ByteFile { get; set; }

        /// <summary>
        /// 文件名称
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// 文件类型
        /// </summary>
        public string FileType { get; set; }

        private System.IO.MemoryStream _Stream = null;
        /// <summary>
        /// 文件
        /// </summary>
        public System.IO.MemoryStream Stream 
        {
            get 
            {
                if( _Stream == null)
                {
                    _Stream = new System.IO.MemoryStream(ByteFile);
                }
                return _Stream;
            }
        }

        /// <summary>
        /// 判断一个类的是否可以使用SocketFile表示
        /// </summary>
        /// <param name="type">需要判断的类型</param>
        /// <returns>type继承了SocketFile或=SocketFile则返回true</returns>
        public static bool IsSocketFileType(Type type)
        {
            if(type.BaseType == null)
            {
                return false;
            }
            Type SocketFileType = typeof(SocketFile);
            if (type.BaseType.Equals(SocketFileType))
            {
                return true;
            }
            if (type.Equals(SocketFileType))
            {
                return true;
            }
            else if (type.BaseType.Equals(typeof(object)))
            {
                return false;
            }
            return IsSocketFileType(type.BaseType);
        }

        /// <summary>
        /// 将当前实体转换为他的子类或本身
        /// </summary>
        /// <param name="type">需要转换的实体</param>
        /// <returns></returns>
        public object Convert(Type type)
        {
            if (type.Equals(typeof(SocketFile)))
            {
                return this;
            }
            SocketFile socketFile = type.Assembly.CreateInstance(type.FullName) as SocketFile;
            if (socketFile == null)
            {
                return socketFile;
            }
            socketFile.FileName = this.FileName;
            socketFile.FileType = this.FileType;
            socketFile.ByteFile = this.ByteFile;
            return socketFile;
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="path"></param>
        public void Save(string path)
        {
            System.IO.File.WriteAllBytes(path, this.ByteFile);
        }
    }
}
